package com.soft.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import com.soft.entity.Worklog;
import com.soft.service.WorklogService;

/**
 * 工作日志接口（/worklog）：
 * - 新增/修改/删除/单查/列表
 * - 列表在未传分页参数时返回数组（向后兼容）；传入 page/size 则返回分页结构
 */
@RestController
@RequestMapping("/worklog")
public class WorklogController {
    @Autowired
    private WorklogService worklogService;

    /** 新增日志：校验必要字段并返回 {id} */
    @PostMapping("/add")
    public Map<String, Object> addWorklog(@RequestBody Worklog worklog) {
    // 1) 基础校验：避免后续出现空指针或数据库约束错误
        if (worklog == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体为空");
        }
        if (worklog.getTitle() == null || worklog.getTitle().trim().isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少标题");
        }
        if (worklog.getContent() == null || worklog.getContent().trim().isEmpty()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少内容");
        }
        if (worklog.getLogDate() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少日期");
        }
        if (worklog.getCreatorId() == null || worklog.getCreatorId() <= 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少或非法的创建人");
        }
        try {
            // 2) 调用服务层保存（可能包含敏感词过滤、字段规范化等）
            boolean ok = worklogService.saveWorklog(worklog);
            if (!ok) {
                throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "保存失败");
            }
            // 3) 返回主键给前端，用于路由跳转或刷新
            Map<String, Object> resp = new HashMap<>();
            resp.put("id", worklog.getWorklogId());
            return resp;
        } catch (DataIntegrityViolationException ex) {
            // 典型于外键不满足（relatedScheduleId/relatedTeamId/creatorId）
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "外键约束失败：请检查关联ID是否存在");
        } catch (RuntimeException ex) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
        }
    }

    /** 更新日志：按字段非空进行合并更新 */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public boolean updateWorklog(@RequestBody Worklog worklog) {
        // 1) 参数完整性校验
        if (worklog == null || worklog.getWorklogId() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少worklogId");
        }
        // 2) 读取原记录用于“按需合并”
        Worklog db = worklogService.getWorklogById(worklog.getWorklogId());
        if (db == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "日志不存在");
        }
        // 3) 仅合并非空字段，避免把必填字段更新为 null
        if (worklog.getTitle() != null) db.setTitle(worklog.getTitle());
        if (worklog.getContent() != null) db.setContent(worklog.getContent());
        if (worklog.getLogDate() != null) db.setLogDate(worklog.getLogDate());
        if (worklog.getCreatorId() != null) db.setCreatorId(worklog.getCreatorId());
        if (worklog.getRelatedScheduleId() != null) db.setRelatedScheduleId(worklog.getRelatedScheduleId());
        if (worklog.getRelatedTeamId() != null) db.setRelatedTeamId(worklog.getRelatedTeamId());
        try {
            // 4) 执行更新，服务层可做审计/更新时间等处理
            return worklogService.updateWorklog(db);
        } catch (DataIntegrityViolationException ex) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "外键约束失败：请检查关联ID是否存在");
        } catch (RuntimeException ex) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
        }
    }

    /** 删除日志（按ID） */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public boolean deleteWorklog(@PathVariable Integer id) {
        return worklogService.deleteWorklog(id);
    }

    /** 获取单条日志（按ID） */
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public Worklog getWorklog(@PathVariable Integer id) {
        return worklogService.getWorklogById(id);
    }

    /**
     * 列表查询：支持 creatorId/teamId 过滤；
     * - 无分页参数：返回数组
     * - 传 page/size：返回 {records,total,page,size}
     */
    @GetMapping("/list")
    public Object listWorklogs(@RequestParam(required = false) Integer creatorId,
                               @RequestParam(required = false) Integer teamId,
                               @RequestParam(required = false) Integer page,
                               @RequestParam(required = false) Integer size) {
    // 1) 若未传分页参数，则保持向后兼容：返回数组
        if (page == null && size == null) {
            if (creatorId == null && teamId == null) {
                return worklogService.listWorklogs();
            }
            return worklogService.listWorklogsBy(creatorId, teamId);
        }
    // 2) 对分页参数做边界保护
    int p = page == null ? 1 : Math.max(1, page);
    int s = size == null ? 10 : Math.max(1, Math.min(size, 200));
    // 3) 分页查询与总数统计
    long total = worklogService.countWorklogs(creatorId, teamId);
    List<Worklog> records = worklogService.listWorklogsPage(creatorId, teamId, p, s);
    // 4) 组装统一分页响应结构
    Map<String, Object> resp = new HashMap<>();
        resp.put("records", records);
        resp.put("total", total);
        resp.put("page", p);
        resp.put("size", s);
        return resp;
    }
}
